<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use app\common\model\Address;
use app\common\model\CouponLog;
use app\common\model\GoodsSku;
use app\common\model\Message;
use app\common\model\OrderAddress;
use app\common\model\OrderInvoice;
use app\common\model\ShopApply;
use app\common\model\UserDonate;
use app\common\model\UserReserve;
use app\common\model\UserScoreLog;
use fast\Random;
use think\cache\driver\Redis;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Validate;
use app\common\model\UserApply;
use app\common\validate\UserApply as UserApplyValidate;
use app\common\model\SendLog;
use app\common\model\Order as MyModel;
use app\common\model\User;
use app\common\model\Goods;
use app\common\model\Goods1;
use app\common\model\OrderGoods;
use app\common\model\GoodsDonate;
/**
 * 订单1-1-2
 */
class Order extends Api
{
    protected $noNeedLogin = [''];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }

    /*
     * 向我捐增订单-预览
     * */
    public function orderDonatePreview(){
        $userId = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $user_donate_id = input('user_donate_id/d');//捐增id
        $where['id']=$address_id;
        $where['user_id']=$userId;
        $address  = Address::where($where)
            ->field('id,user_id,name,phone,city,address')
            ->find();
        $info['address']=$address;
        $where=[];
        $where['id']=$user_donate_id;
        $UserDonate = UserDonate::where($where)
            ->field('id,name,images,is_new,note,user_id')
            ->find();
        if($UserDonate['user_id']==$userId){
            $this->error('自己不可捐增自己');
        }
        $where=[];
        $where['id']=$UserDonate['user_id'];
        $userinfo = User::where($where)
            ->field('id,nickname,avatar')
            ->find();
        $info['goods']=$UserDonate;
        $info['goods']['user']=$userinfo;
        $info['goods']['send']=1;
        $this->success('成功',$info);
    }
    /**
     * 向我捐增-确认接收
     * */
    public function orderDonateAffirm(){
        $userId = $this->auth->id;
//        $address_id = input('address_id/d');//地址id
        $user_donate_id = input('user_donate_id/d');//捐增id

//        $where['id']=$address_id;
//        $where['user_id']=$userId;
//        $address  = Address::where($where)
//            ->field('id,user_id,name,phone,province,city,area,address')
//            ->find();
//        if(!$address){ $this->error('地址不存在'); }
        $whe['id']=$user_donate_id;
        $UserDonate = UserDonate::where($whe)->find();

        if(!$UserDonate) { $this->error('捐赠方不存在'); }

        if($UserDonate['status']!=1){ $this->error('请不要重复操作'); }
        $ShopApply = ShopApply::where(['id'=>$UserDonate['shop_id']])->find();
        $user = User::get($userId);
//        dd($user['send']);
        if($user['send']<1){
            $this->error('福报种子不足');
        }
        User::send(1,$userId,2,2);
        User::send(1,$UserDonate['user_id'],2,1);
//        $city = $address['province'].'/'.$address['city'].'/'.$address['area'];

        $UserDonate->status = '2';
        $UserDonate->donate_city = $ShopApply['city'];
        $UserDonate->donate_name = $ShopApply['username'];
        $UserDonate->donate_mobile = $ShopApply['mobile'];
        $UserDonate->donate_address = $ShopApply['address'];

        //快递
        $c = explode('/',$UserDonate['city']);
        $dc = explode('/',$UserDonate['donate_city']);
        //发件人信息
        $senderInfo['senderName']='福报';
        $senderInfo['senderMobile']=$UserDonate['mobile'];
        $senderInfo['senderProvince']=$c[0];//省
        $senderInfo['senderCity']=$c[1];//市
        $senderInfo['senderDistrict']=$c[2];//区
        $senderInfo['senderAddress']=$UserDonate['address'];

        //收件人信息
        $receiveInfo['receiverName']=$UserDonate['donate_name'];
        $receiveInfo['receiverMobile']=$UserDonate['donate_mobile'];
        $receiveInfo['receiverProvince']=$dc[0];//省
        $receiveInfo['receiverCity']=$dc[1];//市
        $receiveInfo['receiverDistrict']=$dc[2];//区
        $receiveInfo['receiverAddress']=$UserDonate['donate_address'];
        $aa =  express($senderInfo,$receiveInfo,$UserDonate['order_no']);
        $data = json_decode($aa);
        if('0000'==$data->statusCode){
            $billCode = $data->result->billCode;
            $UserDonate->logistic_num=$billCode;
        }

        if($UserDonate->save()){
            $this->success('成功');
        }
        $this->error('失败');
    }
    /**
     * 向我捐增拒绝
     * */
    public function orderDonateRefuse(){
        $user_donate_id = input('user_donate_id/d');//捐增id
        $whe['id']=$user_donate_id;
        $UserDonate = UserDonate::where($whe)->find();
        if(!$UserDonate) { $this->error('捐赠方不存在'); }
        if($UserDonate->status!='1'){
            $this->error('不能重复操作');
        }
        $UserDonate->status='-1';
        $UserDonate->save();
        $this->success('成功');
    }

    /**
     * 闲置商品  开始
     * */
    /**
     * GoodsDonate
     * 闲置商品预览
     * */
    public function GoodsDonatePreview(){
        $userId = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $goods_id= input('goods_id/d');//商品id
        $goods_num= input('goods_num/d');//购买数量
        if($address_id){
            $where['id']=$address_id;
        }else{
            $where['is_default']=1;
        }
        $where['user_id']=$userId;
        $address  = Address::where($where)
            ->field('id,user_id,name,phone,province,city,area,address,is_default')
            ->find();
        $info['address']=$address;
        //闲置商品详情
        $GoodsDonate = GoodsDonate::getInfo($goods_id);

        if($GoodsDonate['state']==2){
            $this->error('该商品已被领取');
        }
        if($GoodsDonate['shop_id']==$userId){
            $this->error('自己不可购买自己商品');
        }

        $info['goods']=$GoodsDonate;
        $info['goods']['goods_num']=$goods_num;
        //运费
//        $allFreight= $this->allFreight($GoodsDonate,$address['id'],$goods_num);

//        $info['logistics']=$allFreight;//物流选择
//        $info['logistics']=$GoodsDonate['freight'];//物流选择
        $info['logistics']=15;//物流选择
        $this->success('成功',$info);
    }
    /**
     * 闲置商品 订单提交
     * */
    public function orderGoodsDonateadd(){

        $userId = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $goods_id= input('goods_id/d');//商品id
//        $goods_num= input('goods_num/d');//购买数量
        $remarks= input('remarks');//备注
        $user_invoice_id= input('user_invoice_id');//发票
        $where['id']=$address_id;
        $where['user_id']=$userId;
        $address  = Address::where($where)
            ->field('id,user_id,name,phone,city,address')
            ->find();
        $info['address']=$address;
        //闲置商品详情
        $GoodsDonate = GoodsDonate::getInfo($goods_id);
        if(!$GoodsDonate){
            $this->error('商品错误');
        }
        $info['goods']=$GoodsDonate;
//        $info['goods']['goods_num']=$goods_num;
        //运费
        $allFreight= $GoodsDonate['freight'];
        $types=1;
//        // 启动事务
//        Db::startTrans();
//        try {











            $add_id = OrderAddress::OrderAddressAdd($address_id,$types);

            $order_sn = order_no();
            $order['order_sn'] = $order_sn;
            $order['user_id'] = $userId;
            $order['order_price'] =  $allFreight;
            $order['createtime'] = time();
            $order['address_id'] = $add_id;
            $order['sell_id'] = $GoodsDonate['user']['id'];
            $order['freight'] = $allFreight;
            $order['remarks'] = $remarks;
            $order['type'] = $types;
            $order['pay_price'] =$allFreight;
            $order['parent_id'] ='-2';

//            //快递
//            //发件人信息
//            $senderInfo['senderName']=$GoodsDonate['username'];
//            $senderInfo['senderMobile']=$GoodsDonate['usemobile'];
//            $senderInfo['senderProvince']=$GoodsDonate['province'];//省
//            $senderInfo['senderCity']=$GoodsDonate['city'];//市
//            $senderInfo['senderDistrict']=$GoodsDonate['area'];//区
//            $senderInfo['senderAddress']=$GoodsDonate['address'];
//
//            //收件人信息
//            $receiveInfo['receiverName']=$address['name'];
//            $receiveInfo['receiverMobile']=$address['phone'];
//            $receiveInfo['receiverProvince']=$address['province'];//省
//            $receiveInfo['receiverCity']=$address['city'];//市
//            $receiveInfo['receiverDistrict']=$address['area'];//区
//            $receiveInfo['receiverAddress']=$address['address'];
//            $aa =  express($senderInfo,$receiveInfo,$order_sn);
//            $data = json_decode($aa);
//            if('0000'==$data->statusCode){
//                $billCode = $data->result->billCode;
//                $order['logistic_num'] =$billCode;
//                $order['logistic_code'] ='中通快递';
//            }


            $thisOrder = MyModel::create($order);

            if(empty($thisOrder['id'])){
                // 回滚事务
//                Db::rollback();
                $this->error('福袋不足');
            }
            //插入子订单商品
            MyModel::orderGoodsAdd($GoodsDonate,$thisOrder['id'],$types);

            if(!empty($user_invoice_id))
                OrderInvoice::OrderInvoiceAdd($user_invoice_id,$thisOrder['id'],$types, $order['pay_price']);
        $GoodsDonate = GoodsDonate::get($goods_id);
        $GoodsDonate->state=2;
        $GoodsDonate->save();


//        Message::getOrderAdd($thisOrder);
            // 提交事务
//            Db::commit();
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $this->error($e);
//        }
        $is_pay=0;
        if($allFreight>0){
            $is_pay = 1;
        }
        $this->success('成功',['order_sn'=>$order_sn,'is_pay'=>$is_pay]);

    }

    /**
     * 兑换-订单预览
     * */
    public function orderGoodsPreview(){
        $user_id = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $sku_id = input('sku_ids/d');//规格id
        $goods_num = input('goods_num/d');//购买数量id
        $type  = input('type',2);// 类型 0 爆品 1 捐增 2 兑换
//        $remarks  = input('remarks');//
        switch ($type){
            case 0:
                $goods_info  = GoodsSku::getGoodsInfo($sku_id,$type);
                break;
            case 1:
                $goods_info='';
                break;
            case 2:
                $goods_info=GoodsSku::getGoods1Info($sku_id,$type);
                break;
        }
        if(empty($goods_info)){
            $this->error('商品信息有误');
        }


        if($goods_info['shop_id']==$user_id){
            $this->error('自己不可购买自己商品');
        }
        if($address_id){
            $where['id']=$address_id;
        }else{
            $where['is_default']=1;
        }

        $where['user_id']=$user_id;

        $address  = Address::where($where)
            ->field('id,user_id,name,phone,province,city,area,address,is_default')
            ->find();
        if(!$address){ $address=null; }else{ $address_id = $address['id']; }

        if($type==2){
            $whe['goods1.id']  = $goods_info['gid'];
            $whe['goods1.state']  = 1;
            $whe['goods1.status']  = 1;
            $Goods = Goods1::where($whe)->with('admin')->find();
        }else{
            $whe['goods.id']  = $goods_info['gid'];
            $whe['goods.state']  = 1;
            $whe['goods.status']  = 1;
            $Goods = Goods::where($whe)->with('admin')->find();
        }

//        $Goods->visible(['id,name,thumbnailimage']);
        $Goods->getRelation('admin')->visible(['company_name','logo','city1']);
        $Goods['nickname'] = $Goods['admin']['company_name'];
        $Goods['avatar'] = $Goods['admin']['logo'];
        $Goods['city'] = $Goods['admin']['city1'];
        $set = get_set();
        $Goods->send =$set['conversion'];
        if(!$Goods) { $this->error('商品不存在'); }

        $info['address'] = $address;
        $info['goods'] = $Goods;
        $info['goods']['goods_num']=$goods_num;
        $info['goods']['sku_name']=$goods_info['sku_name'];
        //运费
        $allFreight= $this->allFreight($Goods,$address_id,$goods_num);

//        dd($allFreight);
        $info['logistics']=$allFreight;//运费
//        $info['all_price']=$allFreight+$goods_info['price'];//总价
        $info['all_price']=$allFreight;//总价
        $this->success('成功',$info);
    }

//
//爆品 ----- 订单信息
//
    /**
     * 爆品-订单预览
     * */
    public function orderGoods1Preview(){
        $user_id = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $sku_ids = input('sku_ids');//规格id
        $goods_num = input('goods_num/d');//购买数量id
        $type  = input('type',0);// 类型 0 爆品 1 捐增 2 兑换
        $buys_type = input('buys_type/d');//1是直接下单2是购物车来的
        $Cache = new Redis();
        $spec_ids = [];
        //商品来源
        if($buys_type==1){
            $spec_ids = $sku_ids;
        }else{
            $redis = $Cache->handler();
            $redis_key =  'fubao_shop_cart_' . $user_id .'_'.$type;
            $goods_info = array_reverse($redis->hkeys($redis_key));
            foreach ($goods_info as $keys => $values) {
                $g_con = explode('_', $values);
                $goods_id = $g_con[0];
                $sku_id = $g_con[1];
                $sku_arr = explode(',', $sku_ids);
                $buys_num = $redis->hget($redis_key, $values);
                foreach ($sku_arr as $ke => $va) {
                    if ($sku_id == $va) {
                        $spec_ids[] = $sku_id;
                        $spec_count_map[$sku_id] = $buys_num;
                        $ret[$keys]['goods_id'] = $goods_id;
                    }
                }
            }
        }
        $goodsSku = new GoodsSku();
        $goodsList = $goodsSku->getGoodsList($spec_ids,$type);
        $goodsList = toArray($goodsList);
        if (empty($goodsList)) {
            $this->success('请求成功!', ['list' => []]);
        }
        if ($buys_type == 2) {//从购物车里获取
            $goods_ids = assoc_unique($ret, 'goods_id');
            $goods_ids_arr = array_column($goods_ids, 'goods_id');//二维数组转一维数组
        } else {
            $goods_ids_arr = explode(',', $goodsList[0]['gid']);
        }
        $goodsModel = model('app\common\model\Goods');
        $shop_ids = $goodsModel->with(['admin'])->whereIn('goods.id', $goods_ids_arr)->select();//查询商家
        //判断当前优惠券所属的商品
        foreach ($shop_ids as $row) {
            $row->visible(['id', 'shop_id']);
            $row->visible(['admin']);
            $row->getRelation('admin')->visible(['company_name','logo','city1']);
        }
        $shop_ids = toArray($shop_ids);
        $shop_ids = assoc_unique($shop_ids, 'shop_id');



        if($address_id){
            $where['id']=$address_id;
        }else{
            $where['is_default']=1;
        }
        $where['user_id']=$user_id;
        $address  = Address::where($where)
            ->field('id,user_id,name,phone,province,city,area,address,is_default')
            ->find();

        if(!$address){ $address=null; }else{ $address_id = $address['id']; }


        $argv = [];
        $all_price = 0;
        $allFreight = 0;
        $Freight = 0;
        $godos_type = 0;//0 正常 2 预售
        foreach ($shop_ids as $k=>$v){
            $argv[$k]['nickname'] = $v['admin']['company_name'];
            $argv[$k]['avatar'] = $v['admin']['logo'];
            $argv[$k]['shop_id'] = $v['shop_id'];
            $argv[$k]['city'] = $v['admin']['city1'];
            $shop_price = 0;

            foreach ($goodsList as $key => &$goods){
                $goods['buy_num'] = $buys_type == 1 ? $goods_num : $spec_count_map[$goods['id']];

                if($type==0){
                    //判断商品是否为 type 1=预约商品,2=预售商品
                    $goodsInfo  = $this->is_goods_type($goods);
                    if(!empty($goodsInfo)){
                        $this->error($goodsInfo);
                    }

                    if($goods['type']==2){
                        $goods['price']=$goods['earnest'];
                        $godos_type = 1;
                    }
                }
                //判断商户
                if ($goods['shop_id'] == $v['shop_id']) {

                    $goods['all_price'] = $goods['price'] * $goods['buy_num'];
                    $argv[$k]['goods'][] = $goods;
                    $shop_price += $goods['price'] * $goods['buy_num'];
                    $all_price += $goods['price'] * $goods['buy_num'];
                    $buy_num = $buys_type == 1 ? $goods_num : $spec_count_map[$goods['id']];
                    // 计算邮费
                    $Freight += $this->allFreight($goods,$address_id,$buy_num);
//                    dd($Freight);
                    $allFreight+=$Freight;
                    $argv[$k]['Freight'] =$Freight;
                }
            }
//            $argv[$k]['allFreight'] =$allFreight;
            $argv[$k]['shop_price'] = $shop_price;
        }

        $set = get_set();


        $info['address'] = $address;
        $info['goods'] = $argv;
        $info['logistics']=$allFreight;//总运费
        $info['all_price']=$allFreight+$all_price;//总价

        $info['send'] = $set['conversion'];
        $info['godos_type'] = $godos_type;


        $this->success('成功',$info);
    }
    /**
     * 订单提交
     * */
    public function orderGoodsAdd(){
        $user_id = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $userBuyNum = input('userBuyNum/d');//商品数量
        $remarks = input('remarks/d');//备注
        $user_invoice_id = input('user_invoice_id');// 发票id
        $buys_type = input('buys_type/d',1);//1是直接下单2是购物车来的
        $types = input('type',0);//类型:0=爆品,1=捐增,2=兑换
        $Cache = new Redis();
        $sku_ids = input('sku_ids', '');
        if (!$buys_type || !$sku_ids) {
            $this->error('参数不完整!');
        }
        //1=捐增 不能为捐增提交
        if($types==1){
            $this->error('类型错误!');
        }
        //查询当前用户收货地址
        if (!$address_id) {
            $this->error('请选择地址!');
        }
        $addressInfo = toArray(Address::get(['id' => $address_id]));
        if (!$addressInfo) {
            $this->error('收货地址不存在');
        }
        //商品来源
        if($buys_type==1){
            $spec_ids = $sku_ids;
        }else{
            $redis = $Cache->handler();
            $redis_key =  'fubao_shop_cart_' . $user_id .'_'.$types;
//            dd($redis_key);
            $goods_info = array_reverse($redis->hkeys($redis_key));
            foreach ($goods_info as $keys => $values) {
                $g_con = explode('_', $values);
                $goods_id = $g_con[0];
                $sku_id = $g_con[1];
                $sku_arr = explode(',', $sku_ids);
                $buys_num = $redis->hget($redis_key, $values);
                foreach ($sku_arr as $ke => $va) {
                    if ($sku_id == $va) {
                        $spec_ids[] = $sku_id;
                        $spec_count_map[$sku_id] = $buys_num;
                        $ret[$keys]['goods_id'] = $goods_id;
                    }
                }
            }
        }
        $goodsSku = new GoodsSku();
        $goodsList = $goodsSku->getGoodsList($spec_ids,$types);
//        dd($goodsList);
        $goodsList = toArray($goodsList);
        if (empty($goodsList)) {
            $this->success('请求成功!', ['list' => []]);
        }
        if ($buys_type == 2) {//从购物车里获取

            $goods_ids = assoc_unique($ret, 'goods_id');
            $goods_ids_arr = array_column($goods_ids, 'goods_id');//二维数组转一维数组
        } else {
            $goods_ids_arr = explode(',', $goodsList[0]['gid']);
        }
        if($types==2){
            $goodsModel = model('app\common\model\Goods1');
            $shop_ids = $goodsModel->with(['admin'])->whereIn('goods1.id', $goods_ids_arr)->select();//查询商家
        }else{
            $goodsModel = model('app\common\model\Goods');
            $shop_ids = $goodsModel->with(['admin'])->whereIn('goods.id', $goods_ids_arr)->select();//查询商家
        }

//        //判断当前优惠券所属的商品
        foreach ($shop_ids as $row) {
            $row->visible(['id', 'shop_id']);
            $row->visible(['admin']);
            $row->getRelation('admin')->visible(['company_name']);
        }
        $shop_ids = toArray($shop_ids);
        $shop_ids = assoc_unique($shop_ids, 'shop_id');
        $argv = [];
        $all_price = 0;
        $allFreight = 0;
        foreach ($shop_ids as $k=>$v){
            $argv[$k]['shop_name'] = $v['admin']['company_name'];
            $argv[$k]['shop_id'] = $v['shop_id'];
            $shop_price = 0;

            foreach ($goodsList as $key => &$goods){
                $goods['buy_num'] = $buys_type == 1 ? $userBuyNum : $spec_count_map[$goods['id']];
                if($types==0){
                    if($goods['earnest']<=0){
                        //判断商品是否为 type 1=预约商品,2=预售商品
                        $goodsInfo  = $this->is_goods_type($goods);
                        if(!empty($goodsInfo)){
                            $this->error($goodsInfo);
                        }
                    }

                }
                //判断商户
                if ($goods['shop_id'] == $v['shop_id']) {

                    $goods['all_price'] = $goods['price'] * $goods['buy_num'];
                    $argv[$k]['goods'][] = $goods;
                    $shop_price += $goods['price'] * $goods['buy_num'];
                    $all_price += $goods['price'] * $goods['buy_num'];
                    $buy_num = $buys_type == 1 ? $userBuyNum : $spec_count_map[$goods['id']];

                   // 计算邮费
                    $allFreight = $this->allFreight($goods,$address_id,$buy_num);

                }
            }
            $argv[$k]['shop_price'] = $shop_price;
            $argv[$k]['Freight'] = $allFreight;
        }
//        if($types==2){
//            $all_price=0;
//        }
//        dd($argv);
        //end
//        // 启动事务
//        Db::startTrans();
//        try {
            $set = get_set();
            $add_id = OrderAddress::OrderAddressAdd($address_id,$types);
            //多商家拆单
            if (count($shop_ids) > 1){
//                    dd($argv);
                    //先生成总的订单
                    $order_sn = order_no();
                    $parent['order_sn'] = $order_sn;
                    $parent['user_id'] = $user_id;
                    $parent['order_price'] = $all_price + $allFreight;
                    $parent['freight'] = $allFreight;
                    $parent['pay_price'] = $all_price ;
                    $parent['address_id'] = $add_id;
                    $parent['remarks'] = $remarks;
                    $parent['is_show'] = 0;
                    $parent['createtime'] = time();
                    $parent['type'] = $types;
                    $parent['send']        = $set['conversion'];
                    $parent['is_invoice']  = !$user_invoice_id?0:1;;

                    $parent['parent_id'] = '-1';
                    $thisOrder = MyModel::create($parent);
//                    dd($thisOrder);
                    if(empty($thisOrder['id'])){
                        // 回滚事务
//                        Db::rollback();
                        $this->error('福袋不足');
                    }
                    $parent_id = $thisOrder['id'];
//                    $parent_id = $orderModel->insertGetId($parent);

                    //再插入子订单
                    foreach ($argv as $k => $v) {
                        $order_price = $v['shop_price'] + $v['Freight'];
                        $pay_price   = $v['shop_price'] ;
                        $this->sendorder($order_price,$pay_price,$parent_id,$v['Freight'],$add_id,$remarks,$v['shop_id'],$types,$v['goods']);
                    }

                $thisOrderId = $parent_id;
                $order['pay_price'] = $thisOrder['pay_price'];
            }else{
                //单商户的
                $order_sn = order_no();
                $order['order_sn'] = $order_sn;
                $order['user_id'] = $user_id;
                $order['order_price'] = $argv[0]['shop_price'] + $argv[0]['Freight'];
                $order['createtime'] = time();
                $order['address_id'] = $add_id;
                $order['sell_id'] = $argv[0]['shop_id'];
                $order['freight'] = $allFreight;
                $order['remarks'] = $remarks;
                $order['type'] = $types;
                $order['pay_price'] = $argv[0]['shop_price'] ;
                $order['parent_id'] ='-2';
                $order['send']        = $set['conversion'];
                $order['is_invoice']  = !$user_invoice_id?0:1;
                if(!empty($argv[0]['goods'][0]['earnest'])){
                    $order['earnest']        = $argv[0]['goods'][0]['earnest'];
                    $order['end_price']        = $order['pay_price']  - $argv[0]['goods'][0]['earnest'];

                    $order['order_sn_end'] = 'WK'.order_no();
                }
//                dddd($argv[0]['goods']);
//                dd($order);
                $thisOrder = MyModel::create($order);
                if(empty($thisOrder['id'])){
                    $this->error('福袋不足');
                }
                $thisOrderId = $thisOrder['id'];

                //插入子订单商品
                $this->ordergoods($argv[0]['goods'],$thisOrderId,$types);
            }
//            dd($user_invoice_id);
            if(!empty($user_invoice_id)){
//                dd(111);
                OrderInvoice::OrderInvoiceAdd($user_invoice_id,$thisOrderId,$types, $order['pay_price']);
            }
            //删除购物车商品
            if($buys_type==2){
                $redis_key= 'fubao_shop_cart_'.$user_id.'_0';
                $goods_info =array_reverse($redis->hkeys($redis_key));
                foreach ($goods_info as $keys => $values) {
                    $g_con = explode('_', $values);
                    $goods_id = $g_con[0];
                    $sku_id = $g_con[1];
                    $sku_arr=explode(',',$sku_ids);
                    foreach ($sku_arr as $ke=>$va){
                        if ($sku_id==$va){
                            $hash_key = $goods_id . '_' . $sku_id;
                            $redis->hdel($redis_key, $hash_key);
                        }
                    }

                }
            }
//        // 提交事务
//            Db::commit();
//        }catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $this->error($e);
//        }
        //is_pay 1 需要支付 0 不需要
        $this->success('成功',['order_sn'=>$order_sn,'is_pay'=>1]);
    }
    /**
     * 支付定金-订单提交
     * */
    public function orderEarnestAdd(){
        $user_id = $this->auth->id;
        $address_id = input('address_id/d');//地址id
        $userBuyNum = input('userBuyNum/d');//商品数量
        $remarks = input('remarks/d');//备注
        $user_invoice_id = input('user_invoice_id/d');// 发票id
        $types = input('types',0);//类型:0=爆品,1=捐增,2=兑换
        $sku_ids = input('sku_ids', '');

        if ( !$sku_ids) {
            $this->error('参数不完整!');
        }
//        //查询当前用户收货地址
        if (!$address_id) {
            $this->error('请选择地址!');
        }
        $addressInfo = toArray(Address::get(['id' => $address_id]));
        if (!$addressInfo) {
            $this->error('收货地址不存在');
        }
        //商品来源
        $spec_ids = $sku_ids;
        $goodsSku = new GoodsSku();
        switch ($types){
            case 0:
                $goodsList = $goodsSku->getGoodsList($spec_ids,$types);
                break;
            case 1:
                $goodsList = $goodsSku->getGoodsList($spec_ids,$types);
                break;
            case 2:
                $goodsList = $goodsSku->getGoods1List($spec_ids,$types);
                break;
        }

        $goodsList = toArray($goodsList);
        if (empty($goodsList)) {
            $this->success('请求成功!', ['list' => []]);
        }
        $goods_ids_arr =$goodsList[0]['gid'];
        $goodsModel = model('app\common\model\Goods');
        $shop = $goodsModel->with(['admin'])->where('goods.id', $goods_ids_arr)->find();//查询商家
        $set = get_set();

        //判断福袋种子
//        $send = User::send($set['conversion'],$user_id,1,2);
//        if(!$send){
//            $this->error('种子数量不足');
//        }

            $all_price = 0;
            $allFreight = 0;
            $da['shop_name'] = $shop['admin']['company_name'];
            $da['shop_id'] = $shop['shop_id'];
            $shop_price = 0;

            foreach ($goodsList as $key => &$goods){
                $goods['buy_num'] = $userBuyNum;
                //判断商户
                if ($goods['shop_id'] == $shop['shop_id']) {
                    $goods['all_price'] = $goods['price'] * $goods['buy_num'];
                    $da['goods'][] = $goods;
                    $shop_price += $goods['price'] * $goods['buy_num'];
                    $all_price += $goods['price'] * $goods['buy_num'];
                    $buy_num = $userBuyNum;
                    //计算邮费
                    $allFreight = $this->allFreight($goods,$address_id,$buy_num);
                }
            }
            $da['shop_price'] = $shop_price;

        //                // 启动事务
//        Db::startTrans();
//        try {
            $add_id = OrderAddress::OrderAddressAdd($address_id,$types);
            //单商户的
            $order_sn             = order_no();
            $order['order_sn']    = $order_sn;
            $order['user_id']     = $user_id;
            $order['order_price'] = $da['shop_price'] + $allFreight;
            $order['createtime']  = time();
            $order['address_id']  = $add_id;
            $order['sell_id']     = $shop['shop_id'];
            $order['freight']     = $allFreight;
            $order['remarks']     = $remarks;
            $order['type']        = $types;
            $order['pay_price']   = $da['shop_price'] ;
            $order['end_price']   = $order['pay_price'] - $shop['earnest'];
            $order['earnest']     = $shop['earnest'];
            $order['parent_id']   = '-2';
            $order['send']        = $set['conversion'];


            $thisOrder = MyModel::create($order);
            if(empty($thisOrder['id'])){
                $this->error('福袋不足');
            }
            $thisOrderId = $thisOrder['id'];
//            $thisOrderId = $orderModel->insertGetId($order);

            $this->ordergoods($da['goods'],$thisOrderId,$types);

            if(!$user_invoice_id)
                OrderInvoice::OrderInvoiceAdd($user_invoice_id,$thisOrderId,$types,$order['pay_price']);
            // 提交事务
//            Db::commit();
//        } catch (\Exception $e) {
//            // 回滚事务
//            Db::rollback();
//            $this->error($e);
//        }
        $this->success('成功',['order_sn'=>$order_sn,'is_pay'=>1]);
    }
    /**
     * 订单支付
     * */
    public function payOrder(){
        $order_sn = input('order_sn');
        $mode = input('mode');//1微信2支付宝
        $orderInfo = MyModel::where('order_sn', $order_sn)->find();
        //1 正常支付 2 支付定金
        $type = input('type',1);
        if ($orderInfo->status != 1) {
            $this->error('当前订单不可执行此操作');
        }
        if ($orderInfo->user_id != $this->auth->id) {
            $this->error('请本人操作');
        }
//        $orderInfo->updatetime = time();
        $orderInfo->mode = $mode;
        $orderInfo->save();
        if($type==2){
            $price = $orderInfo->earnest;
        }else{
//            $price = $orderInfo->pay_price;
            //判断定金是否存在
            if($orderInfo->earnest>0){

                if(empty($orderInfo->earnesttime)){
                    $this->error('定金未支付');
                }

                $price = $orderInfo->end_price;

                if(!empty($orderInfo->order_sn_end)){
                    $order_sn = $orderInfo->order_sn_end;
                }
                //判断预售商品是不是可以支付
                $msg =  $this->is_pay_goods_type($orderInfo['id']);
                if(!empty($msg)){
                    $this->error($msg);
                }

            }else{
                $price = $orderInfo->pay_price;
            }
        }
        //        //支付订单
        //        //TODO $pay_mode 支付方式1 微信2支付宝 $price 支付钱 $order_sn 订单号 $notify_url 回调地址  $body 支付的标题
        (new Pay)->pay($mode, $price, $order_sn, "http://fubao.191292.net/api/pay/courseNotify", '订单支付');
    }


    /**
     * 小程序订单支付
     * */
    public function payOrdermMniapp(){
        $order_sn = input('order_sn');
        $code = input('code');
        $openID = getOpenid($code);
//        dd($openID);
        if(empty($openID)){
            $this->error('信息获取失败');
        }
//        $mode = input('mode',1);//1微信2支付宝
        $orderInfo = MyModel::where('order_sn', $order_sn)->find();
        //0正常支付 1 定金支付 2 尾款支付
        $type = input('type',0);
        if ($orderInfo->status != 1) {
            $this->error('当前订单不可执行此操作');
        }
        if ($orderInfo->user_id != $this->auth->id) {
            $this->error('请本人操作');
        }
        //1 定金 2 尾款 0 正常
        if($type==1){
            $price = $orderInfo->earnest;
        }elseif ($type==2){
            $price = $orderInfo->end_price;
            if(empty($orderInfo->order_sn_end)){
                $order_sn = $orderInfo->order_sn_end;
            }

            //判断预售商品是不是可以支付
            $msg =  $this->is_pay_goods_type($orderInfo['id']);
            if(!empty($msg)){
                $this->error($msg);
            }
        }else{
            $price = $orderInfo->pay_price;
        }

        //        //支付订单
        //        //TODO $pay_mode 支付方式1 微信2支付宝 $price 支付钱 $order_sn 订单号 $notify_url 回调地址  $body 支付的标题http://fubao.191292.net/brvApBTajs.php/index/login.html
        (new Pay)->payMniapp( $price, $order_sn, "http://fubao.191292.net/api/pay/courseNotify", '订单支付',['openid'=>$openID]);
    }


    /**
     * 订单支付
     * */
    public function payOrderWeb(){
        $order_sn = input('order_sn');
        $mode = input('mode');//1微信2支付宝
        $orderInfo = MyModel::where('order_sn', $order_sn)->find();
        //1 定金支付 0 尾款
        $type = input('type',0);
        if ($orderInfo->status != 1) {
            $this->error('当前订单不可执行此操作');
        }
        if ($orderInfo->user_id != $this->auth->id) {
            $this->error('请本人操作');
        }
//        $orderInfo->updatetime = time();
        $orderInfo->mode = $mode;
        $orderInfo->save();
        if($type==1){
            $price = $orderInfo->earnest;
        }else{
//            $price = $orderInfo->pay_price;
            //判断定金是否存在
            if($orderInfo->earnest>0){

                if(empty($orderInfo->earnesttime)){
                    $this->error('定金未支付');
                }

                $price = $orderInfo->end_price;

                if(!empty($orderInfo->order_sn_end)){
                    $order_sn = $orderInfo->order_sn_end;
                }


                //判断预售商品是不是可以支付
                $msg =  $this->is_pay_goods_type($orderInfo['id']);
                if(!empty($msg)){
                    $this->error($msg);
                }

            }else{
                $price = $orderInfo->pay_price;
            }
        }

        //        //支付订单
        //        //TODO $pay_mode 支付方式1 微信2支付宝 $price 支付钱 $order_sn 订单号 $notify_url 回调地址  $body 支付的标题
        (new Pay)->webpay($mode, $price, $order_sn, "http://fubao.191292.net/api/pay/courseNotify", '订单支付');
    }

    /**
     * 通过规格增加订单商品
     * */
    //订单商品添加
    public function ordergoods($list,$thisOrderId,$types){
        $info=[];
        foreach ($list as $ket => $val) {
//            dd($val);
            $orderGoods['order_id'] = $thisOrderId;
            $orderGoods['sku_id'] = $val['id'];
            $orderGoods['goods_id'] = $val['gid'];
            $orderGoods['sku_name'] = $val['sku_name'];
            $orderGoods['goods_num'] = $val['buy_num'];
            $orderGoods['goods_price'] = $val['price'];
            $orderGoods['images'] = $val['thumbnailimage'];
            $orderGoods['goods_name'] = $val['goods_name'];
            if( $val['type']==3){
                $orderGoods['goods_type'] = $val['type'];
            }
            $orderGoods['type'] = $types;
            $info[] = OrderGoods::create($orderGoods);
        }
        return $info;
    }

    //插入子订单
    public function sendorder($order_price,$pay_price,$parent_id,$freight,$add_id,$remarks,$sell_id,$types,$goods){
        $user_id = $this->auth->id;
        $order['order_sn'] = order_no();
        $order['user_id']  = $user_id;
        $order['order_price'] = $order_price;
        $order['pay_price'] = $pay_price;
        $order['parent_id'] = $parent_id;
        $order['freight']   = $freight;
        $order['createtime'] = time();
        $order['address_id'] = $add_id;
        $order['remarks'] = $remarks;
        $order['sell_id'] = $sell_id;
        $order['type']    = $types;
        $info = MyModel::create($order);
        $thisOrderId=$info['id'];
        //插入子订单商品
        $this->ordergoods($goods,$thisOrderId,$types);
    }
    //运费  $goods 商品信息  $address_id地址id $buy_num 购买数量
    public function allFreight($goods,$address_id,$buy_num){
        // 计算邮费
        $allFreight=0;
//        dd($address_id);
        if($goods['is_ship'] == 1 && !empty($address_id)){
            $addressInfo = Address::get($address_id);
            $freight_type = $goods['freight_type']; //0计件 1计重
            if ($freight_type == 0) {
                $type = '2';
            } else {
                $type = '1';
            }
            $logInfo = Db::name('logistics')
                ->where('deletetime', null)
                ->where('id', $goods['freight_id'])
                ->where('type', $type)
                ->find();
//            dd($logInfo);
            if (empty($logInfo)) {
                return '运费模板不存在';
            }
            $freightList = Db::name('logistics_fee')
                ->where('deletetime', null)
                ->where('logistics_id', $goods['freight_id'])
                ->select();

            if (empty($freightList)) {
                return '运费计算错误';
            }
//            dd($freightList);
            $findThis = false;
            foreach ($freightList as $k1 => $v1) {
                if ($v1['city_ids'] == 0) {
                    $first_weight = $v1['first_weight'];//  首重/件
                    $first_weight_price = $v1['first_weight_price'];// 首重/件 价格
                    $next_weight = $v1['next_weight']; // 续重/件
                    $next_weight_price = $v1['next_weight_price'];// 续重/件 价格
                    $findThis = true;
                    break;
                } else {
                    //先进行匹配
                    $cityarr = explode(',', $v1['city_ids']);
                    if (in_array($addressInfo['province_id'], $cityarr)) {
                        $first_weight = $v1['first_weight'];//  首重/件
                        $first_weight_price = $v1['first_weight_price'];// 首重/件 价格
                        $next_weight = $v1['next_weight']; // 续重/件
                        $next_weight_price = $v1['next_weight_price'];// 续重/件 价格
                        if (in_array($addressInfo['city_id'], $cityarr)) {
                            $first_weight = $v1['first_weight'];//  首重/件
                            $first_weight_price = $v1['first_weight_price'];// 首重/件 价格
                            $next_weight = $v1['next_weight']; // 续重/件
                            $next_weight_price = $v1['next_weight_price'];// 续重/件 价格
                        }
                        $findThis = true;
                    }
                }
            }
            if ($findThis) {
                //全国
                if ($freight_type == 0) {
                    //计件
                    $next_num = $buy_num - $first_weight;
                } else {
                    //计重
                    //计算总重量
                    $weights = $buy_num * $goods['weight'];
                    $next_num = $weights - $first_weight;
                }
                if ($next_num <= 0) {
                    $argv['freight'] = $first_weight_price;
                } else {
                    $next_nums = ceil($next_num / $next_weight);
                    $argv['freight'] = $first_weight_price + ($next_nums * $next_weight_price);
                }
            } else {
                return $goods['goods_name'] . '暂不配送该地区';
            }
//            dd($argv['freight']);
        }else{
            $argv['freight'] = 0;
        }
        $allFreight += $argv['freight'];

        return $allFreight;
    }

    //根据商品类型判断活动是否开始
    public function is_goods_type($goods){
        $user_id= $this->auth->id;
        $msg='';
        if($goods['type']==1 || $goods['type']==2 ){
            if($goods['type']==1){
                $type = $goods['type']-1;
                $info = UserReserve::getInfo($goods['gid'],$user_id,$type);
                if(empty($info)){
                    $msg = '您没有预约当前商品';
                }
            }
            if($goods['type']!=2){
                if($goods['starttime']>time()){
                    $msg ='未到开始时间';
                }
                if($goods['endtime']<time()){
                    $msg ='活动已结束';
                }
            }

        }
        return $msg;
    }
    //尾款判断时间
    public function is_pay_goods_type($id){
        $OrderGoods = OrderGoods::where(['order_id'=>$id])->select();
        foreach ($OrderGoods as $k=>$v){
            $goods = Goods::get($v['goods_id']);
//            $msg = $this->is_goods_type($goods);

            if($goods['type']==2 ||$goods['type']==1){
                if($goods['starttime']>time()){
                    $msg ='未到开始时间';
                }
                if($goods['endtime']<time()){
                    $msg ='活动已结束';
                }
            }

            if(!empty($msg)){
                return $msg;
            }
        }
    }
    /**
     * $id 商品id
     * $type 类型:0=爆品,1=捐增,2=兑换
     * */
//    public function aaa($id,$type){
//        switch ($type){
//            case 0:
//                $goods=1;
//                break;
//        }
//        //快递
//        //发件人信息
//        $senderInfo['senderName']=$GoodsDonate['username'];
//        $senderInfo['senderMobile']=$GoodsDonate['usemobile'];
//        $senderInfo['senderProvince']=$GoodsDonate['province'];//省
//        $senderInfo['senderCity']=$GoodsDonate['city'];//市
//        $senderInfo['senderDistrict']=$GoodsDonate['area'];//区
//        $senderInfo['senderAddress']=$GoodsDonate['address'];
//
//        //收件人信息
//        $receiveInfo['receiverName']=$address['name'];
//        $receiveInfo['receiverMobile']=$address['phone'];
//        $receiveInfo['receiverProvince']=$address['province'];//省
//        $receiveInfo['receiverCity']=$address['city'];//市
//        $receiveInfo['receiverDistrict']=$address['area'];//区
//        $receiveInfo['receiverAddress']=$address['address'];
//        $aa =  express($senderInfo,$receiveInfo,$order_sn);
//        $data = json_decode($aa);
//        if('0000'==$data->statusCode){
//            return $billCode = $data->result->billCode;
////            $order['logistic_num'] =$billCode;
////            $order['logistic_code'] ='中通快递';
//        }
//        return false;
//    }

//---------------------------------------------------
// 快递回调
//---------------------------------------------------

    public function express_callback(){

    }
}
